/*
version 1

	by suparerk@
		- lang: ภาษา (th,en)
		- dateRange: จำนวนช่วงของวัน
		- rangeType: ลักษณะการแสดงผลช่วงเวลา (after, before, between)
		- maxSelect: เลือกได้กี่วัน
		- maxColumn: จำนวนปฎิทินต่อ 1 แถว
	
*/

(function($) {
    jQuery.fn.twMultiDatepicker = function(settings) {

        var defaults = {
			lang:"th",
            dateRange:60,
			rangeType:'after',// after, before, between
			MES:null,
			maxSelect:null,
			maxColumn:4,
			onSelected : function(){}
        }

        var options = jQuery.extend(defaults, settings);
		
		var holder = $(this);
		var calenderHolder = '<div class="ui-tw-Calendar-div ui-widget ui-widget-content ui-corner-all ui-helper-clearfix"></div>'
		var calendarMarkup = '<table width="24%" border="0" cellpadding="0" cellspacing="0" class="ui-tw-Calendar"><thead><tr><th height="20" colspan="7" align="center">&nbsp;</th></tr><tr style="font-size:10px"><th height="5" align="center">Su</th><th width="14%" height="5" align="center">Mo</th><th width="14%" height="5" align="center">Tu</th><th width="14%" height="5" align="center">We</th><th width="14%" height="5" align="center">Th</th><th width="14%" height="5" align="center">Fr</th><th width="14%" height="5" align="center">Sa</th></tr></thead><tbody><tr><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td></tr><tr><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td></tr><tr><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td></tr><tr><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td></tr><tr><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td></tr><tr><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td><td align="center">&nbsp;</td></tr></tbody></table>'
		var maxSelect = options.maxSelect;
		
		//default variable
		if(options.lang == "th"){
			var monthName = ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฏาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'];
		}else if (options.lang == "en"){
			var monthName = ['January','February','March','April','May','June','July','August','September','Octobet','November','December'];
		}else{
			var monthName = ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฏาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'];
		}
		
		
		
		//add calendar
		$(holder).before(calenderHolder);
		$(".ui-tw-Calendar-div").hide();
		//
		$(holder).attr("readonly","readonly").toggle(function(){
			$(this).hide();
			///
			var toDay = new Date;
			//thai
			if(options.lang == 'th'){
				var showYear = Number(toDay.getFullYear())+543
			}else{
				var showYear = toDay.getFullYear();
			}
			//for show
			toDate = toDay.getDate() +"/"+  Number(toDay.getMonth()+1) +"/"+ showYear ;
			
			//for cal
			toDay = toDay.getDate() +"/"+  toDay.getMonth() +"/"+ showYear ;
			
			var tmpDate = toDay.split("/");
			var duringUTC = options.dateRange*1000*60*60*24;
			if(options.lang == 'th'){
				var showYear = showYear-543
			}else{
				var showYear = tmpDate[2]
			}
			var nowUTC =  Date.UTC(showYear,tmpDate[1],tmpDate[0]);
			var endUTC = nowUTC+duringUTC;
			
			//end default var
			
			//Create mark up
			if(options.dateRange){
				switch(options.rangeType)
				{
				case "before":
				  //
					var endMonth = new Date;
					endMonth.setTime(nowUTC-duringUTC);
					if(endMonth.getFullYear() == tmpDate[2] ){
						var totalMonth =  Number(tmpDate[1]-endMonth.getMonth());
					}else{
						var totalMonth = (Number(tmpDate[1])+12) - Number(endMonth.getMonth());
					}
					var currentMonth =  new Date; currentMonth.setTime(endMonth); currentMonth = currentMonth.getMonth();
					var currentYear =  new Date; currentYear.setTime(endMonth); currentYear = currentYear.getFullYear();
					
					var displayCondition = "thisUTC > nowUTC || thisUTC < nowUTC-duringUTC";
					
				  break;
				  //
				case "between":
				  //
					var startMonth = new Date;
					startMonth.setTime(nowUTC-(duringUTC/2));
					var endMonth = new Date;
					endMonth.setTime(nowUTC-duringUTC);
					if(endMonth.getFullYear() == showYear ){
						var totalMonth =  Number(tmpDate[1]-endMonth.getMonth());
					}else{
						var totalMonth = (Number(tmpDate[1])+12) - Number(endMonth.getMonth());
					}
					var currentMonth =  new Date; currentMonth.setTime(startMonth); currentMonth = currentMonth.getMonth();
					var currentYear =  new Date; currentYear.setTime(endMonth); currentYear = currentYear.getFullYear();
					
					var displayCondition = "thisUTC > nowUTC+(duringUTC/2) || thisUTC < nowUTC-(duringUTC/2)"; 
				  //
				  break;
				  //
				default:
				 //code to be executed if n is different from case 1 and 2
				 //find mounth in rang
					var endMonth = new Date;
					endMonth.setTime(nowUTC+duringUTC);
					
					if(endMonth.getFullYear() == showYear ){
						var totalMonth = endMonth.getMonth() - tmpDate[1];
						//alert("showYear");
					}else{
						var totalYear = endMonth.getFullYear() - showYear;
						var totalMonth = Number(endMonth.getMonth()) - tmpDate[1];
						totalMonth = (12*totalYear)-totalMonth;
						//alert(totalMonth);
					}
					var currentMonth =  new Date; currentMonth.setTime(nowUTC); currentMonth = currentMonth.getMonth();
					var currentYear =  new Date; currentYear.setTime(nowUTC); currentYear = currentYear.getFullYear();
					
					var displayCondition = "thisUTC < nowUTC || thisUTC > endUTC";
					
				}
				
			}else{
				var totalMonth = 11;
			}
			
			///remove old
			$(".ui-tw-Calendar-div").html("");
			//gen month
			if(totalMonth <= options.maxColumn){
				$(".ui-tw-Calendar-div").width(140*(totalMonth+1))
			}else{
				$(".ui-tw-Calendar-div").width(140*options.maxColumn);
			}
			for (var i=0; i<=totalMonth; i++)
			{	
				
				$(".ui-tw-Calendar-div").append(calendarMarkup).find("table:last").attr({month:currentMonth,year:currentYear});
				//alert(currentMonth)
				if(currentMonth < 11){
					currentMonth = currentMonth+1
				}else{
					currentYear=currentYear+1
					currentMonth = 0;
				}
				
			}
			//show animate
			var message = "";
			if(options.MES != null){
				message = options.MES;
			}
			$(".ui-tw-Calendar-div").append('<div style="clear:both; padding:5px;line-height:24px"><span class="ui-tw-Calendar-close" style=" float:right">Select Date</span><span style=" float:right">'+message+'</span></div>').slideDown(500);
			AssignButtonClass(".ui-tw-Calendar-close","save");
			$(holder).prev("div").find(".ui-tw-Calendar-close").click(function(){ $(holder).click()})
			//assign css to table
			$(".ui-tw-Calendar").addClass("ui-corner-all");
			$(".ui-tw-Calendar th").addClass("ui-state-hover");
			$(".ui-tw-Calendar th[colspan=7]").removeClass("ui-state-hover").addClass("ui-widget ui-widget-header");
			$(".ui-tw-Calendar td").addClass("ui-state-default");
			//apply cannot select
			$(".ui-tw-Calendar").disableSelection();
			
			//enable calendar
			$(".ui-tw-Calendar").each(function(){
				var thisTable = $(this);
				var thisYear = $(this).attr("year");
				
				//thai
				if(options.lang == 'th'){
					var showYear = Number(thisYear)+543
				}else{
					var showYear = Number(thisYear);
				}
				
				var thisMonth = $(this).attr("month");
				$(this).find("th:first").append(monthName[thisMonth] +" "+ showYear)
				
				var dateNum = 1;
				$(this).find("tbody td").each(function(i){
					
						if(i > getFirstDayOfMonth(thisYear,thisMonth) && i <= getFirstDayOfMonth(thisYear,thisMonth)+getDaysInMonth(thisYear,thisMonth)){
							
							$(this).append(dateNum);
							
							//thai
							if(options.lang == 'th'){
								var showYear = Number(thisYear)+543
							}else{
								var showYear = Number(thisYear);
							}
							$(this).data("Date", dateNum +"/"+ thisMonth +"/"+ showYear );
							$(this).data("showDate", dateNum +"/"+ Number(Number(thisMonth)+1) +"/"+ showYear );
							//$(this).append($(this).data("showDate"));
							
							//convert to milisec
							var tmpDate = $(this).data("Date");
							tmpDate = tmpDate.split("/");
							//thai
							if(options.lang == 'th'){
								var showYear = showYear-543
							}else{
								var showYear = tmpDate[2]
							}
							var thisUTC =  Date.UTC(showYear,tmpDate[1],tmpDate[0]);
		
							//Display condition
							if( eval(displayCondition) ){
								$(this).css({'background-color':'#eee',color:'#ccc','border-color':'#ccc'}).addClass("ui-state-disabled");
							}else{
								
								//today
								if($(this).data("showDate") == toDate ){$(this).addClass("ui-state-highlight");}
								
								//hover event
								$(this).hover(function(){$(this).addClass("ui-state-focus")},function(){$(this).removeClass("ui-state-focus")});
								
								//click event
								
								$(this).toggle(function(){
									
									if(maxSelect > 0 ||maxSelect == null ){
										$(this).addClass("ui-state-error");
										//remove Value
										removeValue(holder,$(this).data("showDate"));
										
										if($(holder).val()){$(holder).val($(holder).val()+",")}
										//store value
										$(holder).val( $(holder).val() + $(this).data("showDate"));
									}
									 
									if(options.maxSelect){
										maxSelect = maxSelect - 1;
									}
									
								},function(){
									$(this).removeClass("ui-state-error");
									
									//remove Value
									removeValue(holder,$(this).data("showDate"));
									
								});
								//have val
								if($(holder).val()){
									var getVal = $(holder).val().split(",");
									
									var thisDate = $(this).data("showDate");
									
									var tmpTD = $(this)
									$(getVal).each(function(i){
										if(thisDate == getVal[i]){
											$(tmpTD).trigger('click');
										}
									});
								}
								
							}
							
							dateNum = dateNum+1;
							
						}else{
							$(this).css({'background-color':'#eee',color:'#ccc','border-color':'#ccc'}).addClass("ui-state-disabled");	
						}
						
				});
			});//emd td
			//end 1 click
		},function(){
			$(this).show();
			$(".ui-tw-Calendar-div").slideUp(200).html("");
			if($(this).val()){
				$(this).val(sortDate($(this).val(),options.lang));
			}
			var arrayDate = $(this).val().split(",");
			totalDate = arrayDate.length;
			options.onSelected();
		});

    } //end plug-in
	
	
	function removeValue(holder,removeItem){
		var groupOfDate = $(holder).val().replace(removeItem,"");
		//remove ","  and reindex value
		if(groupOfDate.charAt(0) == ","){
			groupOfDate = groupOfDate.substr(1);
		}else if(groupOfDate.charAt(groupOfDate.length-1) == ","){
			//alert(groupOfDate.length);
			groupOfDate = groupOfDate.substr(0,groupOfDate.length-1);
		}
		if(groupOfDate.split(",,").length > 0) {
			groupOfDate = groupOfDate.replace(",,",",");
		}
		//reindex value
		$(holder).val(groupOfDate);
	}
	
	/* Find the number of days in a given month. */
	function getDaysInMonth (year, month) {
		return 32 - new Date(year, month, 32).getDate();
	}
	
	/* Find the day of the week of the first of a month. */
	function getFirstDayOfMonth (year, month) {
		return new Date(year, month, 1).getDay() -1;
	}
	
	//sort date
	function sortDate(dateArray,lang){
		var thisArray = dateArray.split(",");
		//to milisec
		$(thisArray).each(function(i){
			var convertDate = thisArray[i].split("/");
			var thisDateVal = Date.UTC(Number(convertDate[2])-543,Number(convertDate[1])-1,convertDate[0]);
			thisArray[i] = thisDateVal;
		});
		//sort
		thisArray.sort();
		//to date format
		$(thisArray).each(function(i){
			var convertDate = thisArray[i];
			var sortedDate = new Date;
			sortedDate.setTime(convertDate);
			
			//thai
			if(lang == 'th'){
				var showYear = Number(sortedDate.getFullYear())+543
			}else{
				var showYear = sortedDate.getFullYear();
			}
			//for show
			var thisDateVal = sortedDate.getDate() +"/"+  Number(sortedDate.getMonth()+1) +"/"+ showYear ;
			
			thisArray[i] = thisDateVal;
		});
		
		return thisArray;
		
	}
	
})(jQuery);		